package com.longxi.tianjintianbao.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.model.message.MessageList;
import com.longxi.tianjintianbao.notification.MyNotification;
import com.longxi.tianjintianbao.ui.activity.goodstraffic.SignGoodsReleaseActivity;
import com.longxi.tianjintianbao.ui.activity.login.LoginActivity;
import com.longxi.tianjintianbao.ui.activity.main.AboutActivity;
import com.longxi.tianjintianbao.ui.activity.main.MainActivity;
import com.longxi.tianjintianbao.ui.activity.oa.ChangeFormalDetailActivity;
import com.longxi.tianjintianbao.ui.activity.oa.CopeWithDetailActivity;
import com.longxi.tianjintianbao.ui.activity.oa.CostApplyDetailActivity;
import com.longxi.tianjintianbao.ui.activity.quality.QualityClassListActivity;
import com.longxi.tianjintianbao.ui.activity.rectification.RectificationDetailActivity;
import com.longxi.tianjintianbao.ui.activity.repair.RepairDetailActivity;
import com.longxi.tianjintianbao.ui.activity.task.TaskDetailActivity;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.SoundUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
	private static String TAG = "JIGUANG-Example";

	@Override
	public void onReceive(Context context, Intent intent) {
		try {
			Bundle bundle = intent.getExtras();
			LogUtils.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

			if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
				AppConst.identification = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
				LogUtils.d(TAG, "[MyReceiver] 接收Registration Id : " + AppConst.identification);
				Intent msgIntent = new Intent(AppConst.MESSAGE_REGISTRATION_ID);
				LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
				//send the Registration Id to your server...

			} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
				LogUtils.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
				processCustomMessage(context, bundle);
				SoundUtils.playSound(R.raw.notification);

				if(MainActivity.mainActivity != null){
					MainActivity.mainActivity.refreshHomeMessage();
					MainActivity.mainActivity.refreshMessage();
				}

			} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
//				LogUtils.d(TAG, "[MyReceiver] 接收到推送下来的通知");
//				int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
//				LogUtils.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
//				SoundUtils.playSound(R.raw.notification);

			} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
				LogUtils.d(TAG, "[MyReceiver] 用户点击打开了通知");
				//打开自定义的Activity
//				Intent i = new Intent(MyApplication.getInstance(), MainActivity.class);
//				if(MyApplication.loginUser == null){
//					i = new Intent(MyApplication.getInstance(), LoginActivity.class);
//				}
//				i.putExtras(bundle);
//				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//				context.startActivity(i);

				openNotification(context,bundle);

			} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
				LogUtils.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
				//在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

			} else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
				boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
				LogUtils.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
			} else {
				LogUtils.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
			}
		} catch (Exception e){

		}

	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
				if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
					LogUtils.i(TAG, "This message has no Extra data");
					continue;
				}

				try {
					JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
					Iterator<String> it =  json.keys();

					while (it.hasNext()) {
						String myKey = it.next();
						sb.append("\nkey:" + key + ", value: [" +
								myKey + " - " +json.optString(myKey) + "]");
					}
				} catch (JSONException e) {
					LogUtils.e(TAG, "Get message extra JSON error!");
				}

			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.get(key));
			}
		}
		return sb.toString();
	}

	//send msg to MainActivity
	private void processCustomMessage(Context context, Bundle bundle) {
		if (MainActivity.isForeground) {
			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
			Intent msgIntent = new Intent(AppConst.MESSAGE_RECEIVED_ACTION);
			msgIntent.putExtra(AppConst.KEY_MESSAGE, message);
			if (!TextUtils.isEmpty(extras)) {
				try {
					JSONObject extraJson = new JSONObject(extras);
					if (extraJson.length() > 0) {
						msgIntent.putExtra(AppConst.KEY_EXTRAS, extras);
					}
				} catch (JSONException e) {

				}

			}
			LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
		}
	}

	private void openNotification(Context context, Bundle bundle){
		String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
		String billdid = "";
		int type = 0;

		try {
			JSONObject extrasJson = new JSONObject(extras);
			billdid = extrasJson.optString("billdid");
			type = extrasJson.optInt("type");
		} catch (Exception e) {
			LogUtils.d(TAG, "Unexpected: extras is not a valid json" + e.toString());
			return;
		}

		MyNotification.getMyNotificationInstance().jump(context, billdid, type);
	}

	public void jump(Context mContext, String billdid, int billtype){
		Intent mainIntent = null;
		switch (billtype) {
			case 1://任务单
				mainIntent = new Intent(mContext, TaskDetailActivity.class);
				mainIntent.putExtra(AppConst.BILLID,billdid);
				mainIntent.putExtra(AppConst.STATE,false);
				break;
			case 2://报修单
				mainIntent = new Intent(mContext, RepairDetailActivity.class);
				mainIntent.putExtra(AppConst.BILLID,billdid);
				break;
			case 3://oa
				toApplyActivity(mContext, billdid);
				return;
			case 4://品质检查
				mainIntent = new Intent(mContext, QualityClassListActivity.class);
				mainIntent.putExtra(AppConst.BILLID,billdid);
				mainIntent.putExtra(AppConst.BUILDNAME,"消息");
				break;
			case 5://品质整改
				mainIntent = new Intent(mContext, RectificationDetailActivity.class);
				mainIntent.putExtra(AppConst.BILLID,billdid);
				break;
			case 6://物品放行
				mainIntent = new Intent(mContext, SignGoodsReleaseActivity.class);
				mainIntent.putExtra(AppConst.BILLID,billdid);
				mainIntent.putExtra(AppConst.STATE,"0");
				break;
		}
		if(mainIntent == null){
			MyUtils.showToast("跳转错误");
			return;
		}

		mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
		mContext.startActivity(mainIntent);
	}

	public void toApplyActivity(Context context, String billid) {
		String[] strs=billid.replace(" ", "").split(",");

		Intent mainIntent = null;
		switch (strs[1]) {
			case "13":
				mainIntent = new Intent(context, CostApplyDetailActivity.class);
				mainIntent.putExtra(AppConst.BILLID,strs[0]);
				mainIntent.putExtra(AppConst.STATE,"0");
				break;
			case "280":
				mainIntent = new Intent(context, CopeWithDetailActivity.class);
				mainIntent.putExtra(AppConst.BILLID,strs[0]);
				mainIntent.putExtra(AppConst.STATE,"0");
				break;
			case "19":
				mainIntent = new Intent(context, ChangeFormalDetailActivity.class);
				mainIntent.putExtra(AppConst.BILLID,strs[0]);
				mainIntent.putExtra(AppConst.STATE,"0");
				break;
		}

		mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
		context.startActivity(mainIntent);
	}
}
